<template>
  <div id="loginPanel">
    <!--    <span class="title">北海市货运源头企业信息采集系统</span>-->
    <!--    <div class="line"></div>-->
    <!-- 登录面板 -->
    <div v-show="isLogin">
      <el-form :rules="rules" :model="loginData" ref="loginForm">
        <div class="login_title">
          <span>登入</span>
          <div class="line"></div>
        </div>
        <el-form-item prop="phoneNum">
          <el-input placeholder="请输入您的邮箱/电话/登录名" v-model="loginData.phoneNum">
            <i slot="prefix" class="font_family icon-denglu blue"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            :type="isShowPassword? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="loginData.password"
          >
            <i slot="prefix" class="font_family icon-password blue"/>
            <i slot="suffix" :class="['font_family',
              isShowPassword?'icon-yanjing_kai':'icon-yanjing_bi', 'eyes']" @click="changeShow"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="imgVerify_inputText">
          <el-input
            placeholder="请输入验证码"
            class="imgVerifyInput"
            v-model="loginData.imgVerify_inputText"
            clearable
          >
            <i slot="prefix" class="font_family icon-dunpai- blue"/>
          </el-input>
          <graphic-verification
            id="imgVerify"
            @click.native="refreshCode"
            :identifyCode="identifyCode"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" id="login_btn" @click="loginClick('loginForm')">
            登入
          </el-button>
        </el-form-item>
      </el-form>
      <el-link type="primary" @click="forgetPassword">忘记密码</el-link>
    </div>
    <!-- 忘记密码面板 -->
    <div v-show="!isLogin">
      <el-form :model="forgetForm" :rules="forgetRules" ref="forgetFormRef">
        <div class="login_title"><span>忘记密码</span>
        <div class="line"></div></div>
        <el-form-item prop="email">
          <el-input
            v-model="forgetForm.email"
            placeholder="请输入邮箱"
            class="forgetPasswordInput"
          >
            <i slot="prefix" class="font_family icon-youxiang blue"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="forgetForm.code"
            placeholder="请输入验证码"
            class="forgetPasswordInput verifyCode"
          >
            <i slot="prefix" class="font_family icon-dunpai- blue"/>
          </el-input>
          <el-button type="primary" :disabled="isLoading" class="getVerifyCode" @click="getVCode">
            {{ isLoading ? stopNum + 's' : '获取验证码' }}
          </el-button>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input
            type="password"
            v-model="forgetForm.newPassword"
            placeholder="请输入新密码"
            class="forgetPasswordInput"
          >
            <i slot="prefix" class="font_family icon-password blue"/>
          </el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input
            type="password"
            v-model="forgetForm.rePassword"
            placeholder="请确认密码"
            class="forgetPasswordInput"
          >
            <i slot="prefix" class="font_family icon-password blue"/>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setPassWord" id="confirm_btn"> 确认</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="returnLogin" id="cancel_btn"> 返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import graphicVerification from '@/components/graphicVerification/graphicVerification.vue'
import {
  login,
  getCaptcha,
  verifyCaptcha,
  verifyClient,
  searchMenu,
  sendEmail,
  updPasswordByEmail
} from '@/service/login/login'
// import { getCaptcha, verifyCaptcha, verifyClient, searchMenu } from '@/service/login/login'
import localCache from '@/utils/localCache'

export default {
  components: {
    graphicVerification
  },
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    // 验证邮箱的规则
    var checkPassword = (rule, value, cb) => {
      if (value === this.forgetForm.newPassword) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('密码不相同'))
    }
    return {
      loginData: {
        phoneNum: '',
        password: '',
        // 图形验证码输入框
        imgVerify_inputText: ''
      },
      isLogin: true,
      // 图形验证码输出的字符
      identifyCode: '',
      // 图形验证码ID
      captchaID: '',
      rules: {
        phoneNum: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        imgVerify_inputText: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          },
          {
            min: 4,
            max: 4,
            message: '请输入4位验证码',
            trigger: 'blur'
          }
        ]
      },
      // 忘记密码表单
      forgetForm: {
        email: '',
        code: '',
        newPassword: '',
        rePassword: ''
      },
      // 忘记表单验证
      forgetRules: {
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        code: [
          {
            required: true,
            message: '请输入验证码',
            trigger: 'blur'
          }
        ],
        newPassword: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }
        ],
        rePassword: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          },
          {
            validator: checkPassword,
            trigger: 'blur'
          }
        ]
      },
      isLoading: false,
      timer: null,
      stopNum: 0,
      isShowPassword: false
    }
  },
  created () {
    // 获取图形验证码
    this.getImgCaptcha()
  },
  methods: {
    // 登录
    loginClick (formName) {
      this.$refs[formName].validate(async (valid) => {
        // 表单验证成功就进行登录验证
        if (valid) {
          try {
            const { data } = await login({
              grant_type: 'password',
              captchaId: this.captchaID,
              code: this.loginData.imgVerify_inputText,
              username: this.loginData.phoneNum,
              password: this.loginData.password
            })
            if (data.code === 0) {
              const token = `${data.data.type} ${data.data.token}`
              localCache.setItem('token', token)
              localCache.setItem('name', data.data.userName)
              // 查询菜单
              // this.searchMenu()
              this.$message({
                message: '登录成功',
                type: 'success'
              })
              this.$router.replace('/bashboard/bashboard')
            } else {
              // 重新刷新图形验证码
              this.refreshCode()
              this.$message.error(data.msg)
            }
          } catch (err) {
            this.$message.error('登录失败')
          }
        }
      })

      // 验证图形验证码
      // this.verifyImgCaptcha(this.imgVerify_inputText)
      // 验证客户端
      // this.verifyClient()
    },
    // 获取图形验证码
    async getImgCaptcha () {
      try {
        const { data } = await getCaptcha()
        this.identifyCode = data.data.uri
        this.captchaID = data.data.id
        // 把验证码赋值给输入框（方便测试）
        // this.loginData.imgVerify_inputText = this.identifyCode
      } catch (err) {
        this.$message.error('获取验证码失败')
      }
    },
    // 验证图形验证码
    async verifyImgCaptcha (code) {
      try {
        console.log(this.captchaID)
        const { data } = await verifyCaptcha({
          code,
          captchaId: this.captchaID
        })
        console.log(data)
      } catch (err) {
        this.$message.error('验证验证码失败')
      }
    },
    // 验证客户端
    async verifyClient () {
      try {
        const data = await verifyClient({
          grant_type: 'password',
          client_id: 'newly-system',
          client_secret: 'newly-password',
          scope: 'all',
          password: 'newly-password'
        })
        console.log(data)
      } catch (err) {
        this.$message.error('验证客户端失败')
      }
    },
    // 查询菜单
    async searchMenu () {
      try {
        const data = await searchMenu()
        console.log(data)
      } catch (err) {
        this.$message.error('查询菜单失败')
      }
    },
    forgetPassword () {
      this.isLogin = !this.isLogin
    },
    // 重新获取图形验证码
    refreshCode () {
      this.identifyCode = ''
      this.getImgCaptcha()
    },
    getVCode () {
      this.$refs.forgetFormRef.validateField('email', async (err) => {
        if (err) return
        this.limitTimer()
        const { data: res } = await sendEmail({
          emailAddress: this.forgetForm.email
        })
        if (res.code !== 0) return this.$message.error(res.msg)
        return this.$message.success('验证码发送成功')
      })
    },
    limitTimer () {
      clearInterval(this.timer)
      this.isLoading = true
      this.stopNum = 60
      this.timer = setInterval(() => {
        if (this.stopNum <= 0) {
          clearInterval(this.timer)
          this.isLoading = false
        } else {
          this.stopNum--
        }
      }, 1000)
    },
    setPassWord () {
      this.$refs.forgetFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await updPasswordByEmail({
          email: this.forgetForm.email,
          emailCaptcha: this.forgetForm.code,
          password: this.forgetForm.rePassword
        })
        // console.log(res)
        if (res.code !== 0) return this.$message.error('修改密码失败')
        this.$message.success('修改密码成功')
        this.isLogin = true
      })
    },
    returnLogin () {
      this.$refs.forgetFormRef.resetFields()
      this.isLogin = true
    },
    changeShow () {
      this.isShowPassword = !this.isShowPassword
    }
  }
}
</script>

<style scoped>
#loginPanel {
  width: 898px;
  /*height: 578px;*/
  padding: 47px 133px;
  box-sizing: border-box;
  overflow: visible;
  background-color: rgba(255, 255, 255, 0.75);
  box-shadow: 0px 4px 12px 0px #333;
  border-radius: 15px;
}

.title {
  position: absolute;
  top: -110px;
  left: -115px;
  width: 150%;
  font-size: 48px;
  color: #fff;
  font-weight: 700;
  z-index: 9;
}

.line {
  width: 100px;
  height: 9px;
  transform: scale(0.5) translateX(-50%) translateY(50%);
  background: #006eff;
  border-radius: 9px;
}

.login_title {
  display: flex;
  position: relative;
  font-size: 30px;
  font-weight: 700;
  margin-bottom: 32px;
  flex-direction: column;
  justify-content: space-between;
  align-items: flex-start;
  border-bottom: 1px solid rgba(21, 117, 185, 0.56);
}

.el-input {
  height: 60px;
  margin-bottom: 18px;
}

.el-form-item {
  margin-bottom: 0;
}

.el-form-item >>> .el-form-item__error {
  top: 68%;
}

.el-input >>> .el-input__inner {
  border-radius: 0;
  height: 50px;
  padding-left: 70px;
  font-size: 18px;
  color: rgb(31, 31, 31);
  background-color: rgba(255, 255, 255, 0.35);
  border: 1px solid #CCC;
}

.forgetPasswordInput {
  margin-bottom: 26px;
}

.el-button {
  height: 50px;
  width: 100%;
  background-color: #006eff;
  border-color: #006eff;
  margin-top: 10px;
  font-size: 20px;
}

#confirm_btn {
  margin-top: 15px;
  margin-bottom: 26px;
}

#cancel_btn {
  margin-top: 0;
  color: #006eff;
  background-color: #fff;
}

.el-link {
  color: #4092ff;
  float: right;
  margin-top: 13px;
}

/* 验证码输入框 */
.verifyCode {
  width: 400px;
}

.getVerifyCode {
  width: 200px;
  margin-top: 0;
  margin-left: 29px;
}

/* 图形验证 */
#imgVerify {
  display: inline-block;
  width: 124px;
  height: 38px;
  margin-top: 0;
  margin-left: 29px;
}

.imgVerifyInput {
  width: 400px;
  vertical-align: top;
}

.font_family {
  font-size: 34px;
}

::v-deep .el-input__prefix {
  top: 10%;
  left: 15px;
}

::v-deep .el-input__suffix {
  top: 10%;
  right: 15px;
}

.blue {
  color: #006EFF;
}

.eyes {
  cursor: pointer;
  color: #1e222d;
}
</style>
